package com.shushan.web;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.Constants;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.pages.bean.WXPayBean;
import com.shushan.service.DialRTAService;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.wxapi.WXPayEntryActivity;
import com.shushan.util.PayUtils;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.StringTools;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

/**
 * @ClassName: AdvertWebActivity
 * @Desciption: 广告活动H5
 * @author: yichaohua
 * @date: 2018-11-07
 */
public class AdvertWebActivity extends BaseWebActivity{

    private static final String TAG = "AdvertWebActivity";

    private static final String PAY_URL = "shushanbao://127.0.0.1/extract";

    private IWXAPI api;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        api.registerApp(Constants.APP_ID);

        mWebView.setWebViewClient(mWebViewClient);
    }

    WebViewClient mWebViewClient = new WebViewClient(){

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i(TAG,"url=" + url);

            if(url.startsWith(PAY_URL)){
                if("oppo".equals(BuildConfig.ENVIRONMENT)){
                    PayUtils.orderOppoUrlPay(AdvertWebActivity.this,url);
                }else if(getPackageName().equals(Constants.MASTER_PACKAGE_NAME)){
                    orderPay(url);
                }else {
                    PayUtils.openVipHuawei(AdvertWebActivity.this,url);
                }

            }else {
                view.loadUrl(url);
            }

            return true;
        }

        @Override
        public void onPageFinished(WebView webView, String s) {
            super.onPageFinished(webView, s);

            Log.i(TAG,"onPageFinished() title=" + title);

            if(TextUtils.isEmpty(title)){
                String title = webView.getTitle();
                if (!TextUtils.isEmpty(title)) {
                    titleTextView.setText(title);
                }
            }
        }

    };

    private void orderPay(String url) {
        if(TextUtils.isEmpty(url)){
            showToast("url为空");
            return;
        }

        if(api.getWXAppSupportAPI() < Build.PAY_SUPPORTED_SDK_INT) {
            showToast("您未安装最新版本微信，不支持微信支付，请安装或升级微信版本");
            return;
        }

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.PAY_ORDER);
        urlParse.putValue("phone", SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY))
                .putValue("activity_vip_id",StringTools.getUrlParam(url,"activity_vip_id"))
                .putValue("pay_type","app")
                .putValue("goods_name",StringTools.getUrlParam(url,"goods_name"))
                .putValue("vip_time",StringTools.getUrlParam(url,"vip_time"));

        if(BuildConfig.DEBUG){
            urlParse.putValue("money","0.01");
        }else {
            urlParse.putValue("money",StringTools.getUrlParam(url,"money"));
        }

        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<WXPayBean>() {

                    @Override
                    protected void onCommon() {
                        super.onCommon();

                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(WXPayBean wxPayBean) {
                        if(wxPayBean != null){
                            PayReq req = new PayReq();
                            req.appId			= wxPayBean.appid;
                            req.partnerId		= wxPayBean.partnerid;
                            req.prepayId		= wxPayBean.prepayid;
                            req.nonceStr		= wxPayBean.noncestr;
                            req.timeStamp		= wxPayBean.timestamp + "";
                            req.packageValue	= wxPayBean.packageName;
                            req.sign			= wxPayBean.sign;
                            req.extData			= "app data"; // optional

                            Log.i(TAG,"out_trade_no=" + wxPayBean.out_trade_no);
                            SharedPreferencesUtils.setStringDate(Constants.OUT_TRADE_NO_SHAREPREFERS_KEY,wxPayBean.out_trade_no);
                            WXPayEntryActivity.type = 4;

                            boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
                            if(isChildControl){
                                setAllowBack(true);
                                Intent intent = new Intent(AdvertWebActivity.this,DialRTAService.class);
                                intent.putExtra("rtaType",4);
                                intent.putExtra("allowPackName",Constants.ALLOW_WECHAT_PACK_NAME);
                                startService(intent);
                            }

                            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                            api.sendReq(req);
                        }else {
                            showToast("返回数据为空");
                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }
}
